package ar.fiuba.logger.formatRules;

import java.text.SimpleDateFormat;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import ar.fiuba.logger.LogMessageInterface;

/**
 * The Class DateFormatRule.
 * 
 * This class implements the date format rule. This rule prints the current time and date using Simple Date Format.
 */
public class DateFormatRule implements FormatRuleInterface {
  /**
   * The rule code. This string will be replaced by the rule result.
   */
  private static final String ruleCode = "d";

  /*
   * (non-Javadoc)
   * 
   * @see fiuba.logger.formatRules.FormatRuleInterface#applyFormatRule(java.lang.String)
   */
  @Override
  public String applyFormatRule(String unformattedMessage, LogMessageInterface logMessage) {
    /*
     * This regex will match and store any text with the format: %RuleCode{DateFormat} that doesn't have the percent
     * sign in front of it. For example: If ruleCode is 'd' then it this will match anything like: %d{DateFormat}
     * But it will not match: %%d{DateFormat}
     */
    final String regex = "(?<!%)%" + ruleCode + "\\{([^\\}]*)\\}";

    Pattern p = Pattern.compile(regex);

    Matcher m = p.matcher(unformattedMessage);

    String buffer = unformattedMessage;

    while (m.find()) {
      String dateFormat = m.group(1);

      SimpleDateFormat dateFormatter = new SimpleDateFormat(dateFormat);

      buffer = buffer.replaceFirst(regex, dateFormatter.format(logMessage.getDate()));
    }

    return buffer;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#equals(java.lang.Object)
   */
  @Override
  public boolean equals(Object object) {
    if (this == object)
      return true;
    if (object == null)
      return false;
    if (getClass() != object.getClass())
      return false;
    return true;
  }

  /*
   * (non-Javadoc)
   * 
   * @see java.lang.Object#hashCode()
   */
  @Override
  public int hashCode() {
    return Objects.hashCode(this.getClass());
  }

}
